package com.oasys.utils;

import com.oasys.ecxeption.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件工具类
 */
public final class FileUtils {

    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 存放位置：简历
     */
    public static final String STORAGE_LOCATION_RESUME = "saveFiles/resume/";

    /**
     * 存放位置：发票
     */
    public static final String STORAGE_LOCATION_RECEIPT = "saveFiles/receipt/";

    public static String createFileName(String location, String fileType) {
        if (StringUtils.isAnyBlank(location, fileType)) {
            throw new BusinessException("文件类型不可以为空哦");
        }
        try {
            return getBasePath() + location + getUuidFileName(fileType);
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("生成文件名失败, " + e.getMessage());
        }
    }

    public static String resolveFileType(MultipartFile multipartFile) {
        try {
            byte[] bytes = multipartFile.getBytes();
            if (bytes.length == 0) {
                throw new BusinessException("文件为空");
            }

            StringBuilder hexBuilder = new StringBuilder();
            for (byte aByte : bytes) {
                String hex = Integer.toHexString(aByte & 0xFF);
                if (hex.length() < 2) {
                    hexBuilder.append("0");
                }
                hexBuilder.append(hex);
                if (hexBuilder.length() > 30) {
                    break;
                }
            }
            String header = hexBuilder.toString().toUpperCase();

            String fileType = null;
            for (Map.Entry<String, String> entry : FILE_TYPE_MAP.entrySet()) {
                if (header.startsWith(entry.getKey())) {
                    fileType = entry.getValue();
                    break;
                }
            }

            if (fileType == null) {
                throw new BusinessException("不支持的文件类型");
            }

            return fileType;
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("解析文件失败, " + e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("解析文件失败");
        }

    }

    public static void saveFile(String fileName, MultipartFile multipartFile) {
        try {
            multipartFile.transferTo(new File(fileName));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("文件保存失败");
        }
    }

    public static String createDownloadUri(String location) {
        if (StringUtils.isAnyBlank(location)) {
            throw new BusinessException("生成下载路径失败, 文件路径为空");
        }
        try {
            return "/" + location.replace(getBasePath(), "");
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("生成下载路径失败, " + e.getMessage());
        }
    }

    private static String getUuidFileName(String fileType) {
        return UUID.randomUUID().toString().replace("-", "") + "." + fileType;
    }

    private static String getBasePath() {
        try {
            return ResourceUtils.getURL("classpath:").getPath();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("获取文件保存路径失败");
        }
    }

    private FileUtils() {}

    private static final Map<String, String> FILE_TYPE_MAP = new HashMap<>();

    static {
        FILE_TYPE_MAP.put("255044462d312e".toUpperCase(), "pdf");
        FILE_TYPE_MAP.put("504b0304140006000800".toUpperCase(), "docx");
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000".toUpperCase(), "doc");
        FILE_TYPE_MAP.put("FFD8FF".toUpperCase(), "jpg");
        FILE_TYPE_MAP.put("89504E47".toUpperCase(), "png");
    }
}
